package org.example.service.impl;
/**
 * 登录功能的业务层实现类
 */

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.exception.BusinessException;
import org.example.mapper.UserMapper;
import org.example.pojo.Result;
import org.example.pojo.User;
import org.example.service.LoginService;
import org.example.utils.JwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.UUID;

/**
 * 登录功能的业务层实现类
 */
@Service
public class LoginServiceImpl implements LoginService {

    /**
     * 用来进行网络请求的模板类
     */
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private UserMapper userMapper;

    private static String appId="";

    private static String secret = "";

    /**
     * 微信登录的逻辑
     */
    @Override
    public Result login(String code) throws IOException {
        //通过凭证获取微信用户的openId
        String url = "https://api.weixin.qq.com/sns/jscode2session" +
                "?appid=" +appId
                +"&secret="+secret
                +"&js_code="+code
                +"&grant_type=authorization_code";
        //请求接口获取微信用户信息
        String response = restTemplate.getForObject(url, String.class);
        //json对象
        ObjectMapper objectMapper = new ObjectMapper();
        HashMap hashMap = objectMapper.readValue(response, HashMap.class);
        String openid = (String) hashMap.get("openid");

        //绑定微信用户信息
        User loginUser = userMapper.findUserByOpenId(openid);
        if (loginUser == null){
            User user = new User();
            user.setOpenId(openid);
            //随机的用户名
            user.setName("微信用户"+ UUID.randomUUID().toString().substring(0,6));
            //创建时间
            user.setCreateTime(LocalDateTime.now());
            int saveResult = userMapper.insert(user);
            if (saveResult <= 0){
                throw new BusinessException(500,"微信登录失败");
            }
        }

        //生成token信息
        String token = JwtUtil.generateToken(openid);
        HashMap result = new HashMap();
        result.put("token",token);
        //返回前端
        return Result.success(result);
    }

    @Override
    public Result wxLogin(String code) {
        return null;
    }

    @Override
    public Result getUserCredit(String token) {
        return null;
    }
}